package com.bnlr.lrparking.appui.mine.setting;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.appui.paypwd.AlterPayPswActivity;
import com.bnlr.lrparking.appui.paypwd.SetPayPasswordActivity;
import com.bnlr.lrparking.appui.login.VerificaActivity;
import com.bnlr.lrparking.appui.web.WebActivity;
import com.bnlr.lrparking.constant.SpConstant;
import com.bnlr.lrparking.constant.Urls;
import com.flyco.animation.BounceEnter.BounceTopEnter;
import com.flyco.animation.SlideExit.SlideBottomExit;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.reserve.ExampleUtil;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.util.CommonUtil;
import com.bnlr.lrparking.util.VersionUtils;
import com.bnlr.lrparking.util.update.OkGoUpdateHttpUtil;
import com.bnlr.lrparking.view.CarCommon;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.vector.update_app.UpdateAppBean;
import com.vector.update_app.UpdateAppManager;
import com.vector.update_app.UpdateCallback;
import com.yolanda.nohttp.NoHttp;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;


/**
 * 设置
 *
 * @author Administrator
 * @date 2017/6/7
 */

public class SettingActivity extends BaseActivity {

    private static final String TAG = "SettingActivity";

    @BindView(R.id.tv_nav_title)
    TextView tvNavTitle;
    @BindView(R.id.tv_nav_right)
    TextView tvNavRight;
    @BindView(R.id.iv_nav_right)
    ImageView ivNavRight;
    @BindView(R.id.iv_nav_back)
    ImageView ivNavBack;
    @BindView(R.id.lay_setting00)
    LinearLayout laySetting00;
    @BindView(R.id.lay_setting01)
    LinearLayout laySetting01;
    @BindView(R.id.lay_setting02)
    LinearLayout laySetting02;
    @BindView(R.id.textView3)
    TextView textView3;
    @BindView(R.id.lay_setting03)
    LinearLayout laySetting03;
    @BindView(R.id.textView4)
    TextView textView4;
    @BindView(R.id.lay_setting04)
    LinearLayout laySetting04;
    @BindView(R.id.textView5)
    TextView textView5;
    @BindView(R.id.lay_setting05)
    LinearLayout laySetting05;
    @BindView(R.id.tv_setting_phone)
    TextView tvSettingPhone;
    @BindView(R.id.lay_setting06)
    LinearLayout laySetting06;
    @BindView(R.id.tv_huanchun)
    TextView tvHuanchun;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.lay_setting07)
    LinearLayout laySetting07;
    @BindView(R.id.btn_setting)
    Button btnSetting;
    String phone, paypassword;
    String version = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        ButterKnife.bind(this);
        // 设置标题
        tvNavTitle.setText("设置");
        PackageInfo info = null;
        String appPhone = AppConfig.getInstance().getString("app_phone", "4008097095");
        tvSettingPhone.setText(appPhone);
        try {
            info = getPackageManager().getPackageInfo(this.getPackageName(), 0);
            version = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            // TODO 版本更新，此处为最新版本号前一个版本号
            version = "1.0";
        }
        tvVersion.setText("当前版本号：" + version);

        //getData();
        try {
            tvHuanchun.setText(CommonUtil.getTotalCacheSize(baseContext));
        } catch (Exception e) {
            Log.e(TAG, "onCreate: ", e);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 判断登录按钮是否显示
        paypassword = AppConfig.getInstance().getString("paypassword", "0");
        if (AppConfig.getInstance().getBoolean("isLogin", false)) {
            btnSetting.setVisibility(View.VISIBLE);
        } else {
            btnSetting.setVisibility(View.GONE);
        }
    }

    /**
     * 请求数据， phone 用户手机号
     */
//    @Override
//    public void getData() {
//        super.getData();
//        try {
//            mRequest = NoHttp.createStringRequest(Urls.IP, LrConstant.POST);
//            mRequest.add("action", "GetPhone");
//            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
//            mRequest.add("phonePara", Application.DEVICE_ID);
//            // 添加到请求队列
//            CallServer.getRequestInstance().add(baseContext, mRequest,
//                    new CustomHttpListener<JSONObject>(baseContext, false, null) {
//                        @Override
//                        public void doWork(JSONObject data, String code) {
//                            if (TextUtils.equals("1", code)) {
//                                try {
//                                    phone = data.getJSONObject("data").getString("phone");
////                                    tvSettingPhone.setText(phone);
//                                } catch (Exception e) {
//
//                                }
//                            }
//                        }
//                    }, true);
//
//        } catch (Exception e) {
//            Log.e(TAG, "getData: ", e);
//        }
//    }

    Intent intent = null;

    @Override
    public void doClick(View v) {
        super.doClick(v);
        switch (v.getId()) {
            case R.id.lay_setting00:
                if (AppConfig.getInstance().getBoolean("isLogin", false)) {
                    //修改密码
                    if (paypassword.equals("1")) {
                        startActivity(AlterPayPswActivity.class);
                    }
                    //设置密码
                    else if (paypassword.equals("0")) {
                        startActivity(SetPayPasswordActivity.class);
                    }
                }
                // 未登录，先去登录
                else {
                    startActivity(VerificaActivity.class);
                }
                break;
            // 关于我们
            case R.id.lay_setting01:
                startActivity(AboutActivity.class);
                break;
            // 帮助中心
            case R.id.lay_setting02:
                intent = new Intent(baseContext, WebActivity.class);
                intent.putExtra("tag", 2);
                startActivity(intent);
                break;
            // 服务条款
            case R.id.lay_setting03:
                intent = new Intent(baseContext, WebActivity.class);
                intent.putExtra("tag", 3);
                startActivity(intent);
                break;
            // 意见反馈
            case R.id.lay_setting04:
                if (!AppConfig.getInstance().getBoolean("isLogin", false)) {
                    startActivity(VerificaActivity.class);
                    return;
                }
                startActivity(EditFankuiActivity.class);
                break;
            // 版本说明
            case R.id.lay_setting05:
                intent = new Intent(baseContext, WebActivity.class);
                intent.putExtra("tag", 4);
                startActivity(intent);
                break;
            // 联系我们
            case R.id.lay_setting06:
                CarCommon carCommon = new CarCommon();
                carCommon.phoneDialog(this);
                break;
            // 清除缓存
            case R.id.lay_setting07:
                clearCaChe();
                break;
            // 退出登录
            case R.id.btn_setting:
                View view3 = View.inflate(SettingActivity.this,
                        R.layout.setting_custom_dialog, null);
                // 对话框
                final Dialog dialog2 = new AlertDialog.Builder(SettingActivity.this, R.style.NativeDialog)
                        .create();
                dialog2.show();
                dialog2.getWindow().setWindowAnimations(R.style.dialog_anim_style);
                dialog2.getWindow().setContentView(view3);
                TextView tishi2 = (TextView) view3.findViewById(R.id.text_dialog);
                TextView text_phone = (TextView) view3.findViewById(R.id.text_phone);
                text_phone.setText("确定退出登录？");
                // 取消按钮
                TextView btn_Cancel2 = (TextView) view3.findViewById(R.id.cancle);
                btn_Cancel2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog2.dismiss();
                    }
                });
                // 确定按钮
                TextView btn_OK2 = (TextView) view3.findViewById(R.id.sure);
                btn_OK2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog2.dismiss();
                        AppConfig.getInstance().putString("userName", "");
                        AppConfig.getInstance().putString("uid", "");
                        AppConfig.getInstance().putBoolean("isLogin", false);
                        AppConfig.getInstance().putBoolean(SpConstant.KEY_IS_WX_LOGIN, false);
                        JPushInterface.setAlias(SettingActivity.this, 2019, "");
                        finish();
                    }
                });
                break;
            // 检查更新
            case R.id.lay_setting08:
                updateApp();
                break;
            default:
                // Do nothing
                break;
        }
    }

    /**
     * 清除缓存
     */
    private void clearCaChe() {

        String size = "";
        try {
            size = CommonUtil.getTotalCacheSize(baseContext);
            if (size.endsWith("0K")) {
                tvHuanchun.setText("0K");
                CommonUtil.showToask(baseContext, "当前缓存已经为空，无需清除");
            } else {

                final NormalDialog dialog = new NormalDialog(this);
                dialog.title("提示")
                        .titleTextColor(getResources().getColor(R.color.black_color))
                        .titleTextSize(15)
                        .content("确定要清除所有缓存吗?")
                        .contentTextSize(15)
                        .contentTextColor(getResources().getColor(R.color.gray_color))
                        .btnText("取消", "确定")
                        .btnNum(2)
                        .style(NormalDialog.STYLE_TWO)
                        .btnTextColor(getResources().getColor(R.color.gray_color), getResources().getColor(R.color.colorAccent))
                        .btnTextSize(15, 15)
                        .widthScale(0.8f)
                        .showAnim(new BounceTopEnter())
                        .dismissAnim(new SlideBottomExit())
                        .cornerRadius(7)
                        .show();
                dialog.setCancelable(true);
                dialog.setOnBtnClickL(
                        new OnBtnClickL() {
                            @Override
                            public void onBtnClick() {
                                dialog.dismiss();
                            }
                        },
                        new OnBtnClickL() {
                            @Override
                            public void onBtnClick() {
                                CommonUtil.clearAllCache(baseContext);
                                tvHuanchun.setText("0k");
                                dialog.dismiss();
                            }
                        });

            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    /**
     * 在线更新
     */
    private void updateApp() {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
        Map<String, String> params = new HashMap<String, String>();
        params.put("action", "GetUsingVersion");
        params.put("type", "1");
        new UpdateAppManager
                .Builder()
                //必须设置，当前Activity
                .setActivity(this)
                //必须设置，实现httpManager接口的对象
                .setHttpManager(new OkGoUpdateHttpUtil())
                //必须设置，更新地址
                .setUpdateUrl(Urls.COMMON)
                //以下设置，都是可选
                //设置请求方式，默认get
                .setPost(true)
                //添加自定义参数，默认version=1.0.0（app的versionName）；apkKey=唯一表示（在AndroidManifest.xml配置）
                .setParams(params)
                //设置apk下砸路径，默认是在下载到sd卡下/Download/1.0.0/test.apk
                .setTargetPath(path)
                .setTopPic(R.drawable.top_3)
                .setThemeColor(0xff00CAA3)
                //设置appKey，默认从AndroidManifest.xml获取，如果，使用自定义参数，则此项无效
//                .setAppKey("ab55ce55Ac4bcP408cPb8c1Aaeac179c5f6f")
                .build()
                //检测是否有新版本
                .checkNewApp(new UpdateCallback() {
                    /**
                     * 解析json,自定义协议
                     *
                     * @param json 服务器返回的json
                     * @return UpdateAppBean
                     */
                    @Override
                    protected UpdateAppBean parseJson(String json) {
                        UpdateAppBean updateAppBean = new UpdateAppBean();
                        try {
                            JSONObject object = new JSONObject(json);
                            JSONObject jsonObject = object.getJSONObject("data");
                            String isUpdate = "No";
                            if (VersionUtils.compareVersion(jsonObject.optString("VersioNnumber"), version) > 0) {
                                isUpdate = "Yes";
                            }
                            updateAppBean
                                    //（必须）是否更新Yes,No
                                    .setUpdate(isUpdate)
                                    //（必须）新版本号，
                                    .setNewVersion(jsonObject.optString("VersioNnumber"))
                                    //（必须）下载地址
                                    .setApkFileUrl(jsonObject.optString("LinkUrl"))
                                    //（必须）更新内容
                                    .setUpdateLog(jsonObject.optString("AppContent"))
                                    //大小，不设置不显示大小，可以不设置
                                    .setTargetSize(jsonObject.optString("Size"))
                                    //是否强制更新，可以不设置
                                    .setConstraint(jsonObject.optInt("IsForce") == 1 ? true : false)
                            ;
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        return updateAppBean;
                    }

                    /**
                     * 有新版本
                     *
                     * @param updateApp        新版本信息
                     * @param updateAppManager app更新管理器
                     */
                    @Override
                    public void hasNewApp(UpdateAppBean updateApp, UpdateAppManager updateAppManager) {

                        try {
                            updateAppManager.showDialogFragment();
                        } catch (Exception e) {
                            LogUtils.e(e.getMessage());
                        }

                        // 自定义对话框
                        //showDiyDialog(updateApp, updateAppManager);
                    }

                    /**
                     * 网络请求之前
                     */
                    @Override
                    public void onBefore() {

                    }

                    /**
                     * 网路请求之后
                     */
                    @Override
                    public void onAfter() {

                    }

                    /**
                     * 没有新版本
                     */
                    @Override
                    public void noNewApp() {
                        ToastUtils.showShort("没有新版本");
                        //Toast.makeText(JavaActivity.this, "没有新版本", Toast.LENGTH_SHORT).show();
                    }
                });
    }
}
